/**
 * Copyright (c) 2008, Keisuke Inoue, Syracuse Unviersity
 * All rights reserved.
 *
 */
package edu.syr.iis.web.model;

import java.util.List;
import edu.syr.iis.web.util.HibernateUtil;


import org.hibernate.HibernateException;
import org.hibernate.Session;

/**
 * Manages database operations for Dataset table
 * @author kinoue
 *
 */
public class DatasetManager
{
    /**
     * Returns list of all Dataset database records sorted by daasetId
     */
    public List<Dataset> getDatasets()
    {
	List<Dataset> list = null;
	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	session.beginTransaction();
	
	try
	{
	    list = session.createQuery("FROM Dataset ORDER BY datasetId").list();
	    session.getTransaction().commit();
	}
	catch (HibernateException e)
	{
	    session.getTransaction().rollback();
	    throw e;
	}
	return list;
    }
    
    public Dataset getDataset(int datasetId)
    {
	Dataset dataset = null;
	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	session.beginTransaction();
	
	try
	{
	    dataset = (Dataset) session.createQuery(
		    "FROM Dataset " +
		    " WHERE datasetId = ?").setInteger(0, datasetId).uniqueResult();
	    session.getTransaction().commit();
	}
	catch (HibernateException e)
	{
	    session.getTransaction().rollback();
	    throw e;
	}
	return dataset;
    }
    
    /**
     * Saves a Dataset object.
     */
    public void saveDataset(Dataset dataset)
    {
        Session session = HibernateUtil.getSessionFactory()
                .getCurrentSession();
        session.beginTransaction();
        try
        {
            session.saveOrUpdate(dataset);
            session.getTransaction().commit();
        }
        catch (HibernateException e)
        {
            session.getTransaction().rollback();
            throw e;
        }
    }
    
    /**
     * Deletes Dataset record with matching datasetId 
     */
    public void deleteDataset(int datasetId)
    {
        Session session = 
            	HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();	
        try
        {
            session.delete(session.load(Dataset.class,new Integer(datasetId)));         	    			
            session.flush();
            session.getTransaction().commit();
        }
        catch (HibernateException e)
        {
            session.getTransaction().rollback();
            throw e;
        }
    }
}
